<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic\package;

use OSS\OssClient;
use OSS\Core\OssException;
use think\Db;

class PackageLogic
{
    //1、注册赠送 2、下级购买赠送 请勿随意更改值导致程序数据错误
    CONST REGISTER_GIVE = 1; //注册赠送
    CONST PAY_GIVE = 2; //购买赠送
    CONST REAL_VERIFY_GIVE = 3;//真人认证赠送套餐

    /**
     * User:Simony
     * Function:购买套餐
     * @param $member_id 会员id
     * @param $package_id 套餐id
     * @param $pay_type 支付方式 付款方式：0余额支付 1微信支付 2支付宝支付
     * @return array
     */
    public function buyPackage($member_id, $package_id, $pay_type)
    {

        switch ($pay_type) {
            case 0:
                $res = $this->availablePayPackage($member_id, $package_id);
                return ds_arr($res['code'], $res['msg'], $res['result']);
                break;
            case 1:
                return ds_arr(ERROR, '暂不支持微信支付');
                break;
            case 2:
                return ds_arr(ERROR, '暂不支持支付宝支付');
                break;
            default:
                return ds_arr(ERROR, '支付方式有误');
                break;
        }

    }

    /**
     * User:Simony
     * Function: 余额支付套餐
     * @param $member_id
     * @param $package_id
     * @return array
     */
    public function availablePayPackage($member_id, $package_id)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $packageModel = model('common/package/Package');
        $package = $packageModel->getInfoByID($package_id);
        if (!$package) return ds_arr(ERROR, '当前套餐不存在');

        $price = $package['price'];
        if (floatval($member['available_balance']) < floatval($price)) return ds_arr(JUMP_RECHARGE, '余额不足，还差' . ($price - $member['available_balance']) . '金币,请及时充值');

        //套餐购买记录
        $packageBuyLogModel = model('common/package/PackageBuyLog');
        $expire_end_time = $packageBuyLogModel->getMax(['member_id' => $member_id], 'expire_end_time'); //最大失效时间


        $current_time = time();
        $expire_start_time = $expire_end_time > $current_time ? $expire_end_time + 1 : $current_time + 1;

        $expire_end_time = $expire_start_time + $package['day'] * 86400;
        $add_buy_package_data = [
            'package_id' => $package_id,
            'order_sn' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
            'member_id' => $member_id,
            'pay_type' => 0,  //0余额支付
            'state' => 1,
            'price' => $price,
            'create_time' => $current_time,
            'pay_time' => $current_time,
            'desc' => $package['name'] . '/' . $price,
            'expire_start_time' => $expire_start_time,
            'expire_end_time' => $expire_end_time,
        ];
//        print_r($add_buy_package_data);die;

        $add_buy_package_res = $packageBuyLogModel->add($add_buy_package_data);
        if (!$add_buy_package_res) return ds_arr(ERROR, '添加购买记录失败');

        //余额变更记录
        //变更余额
        $desc = '购买了' . $package['name'];
        $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member_id, -$price, 0, 0, $desc);
        if ($update_available_balance_res['code'] != SUCCESS) return ds_arr($update_available_balance_res['code'], $update_available_balance_res['msg']);

        //使用自动升级可不直接修改等级


        return ds_arr(SUCCESS, '购买成功');

    }

    /**
     * User: Simony
     * Function:赠送套餐 （有可能给上级也有可能送给下级根据 type来定）
     * @param $member_id 下级用户
     * @param $superior_member_id 上级用户
     * @param $type
     */
    public function givePackage($member_id, $type)
    {
        switch ($type) {
            case self::REGISTER_GIVE:
                $res = $this->registerGive($member_id);
                return ds_arr($res['code'], $res['msg'], $res['result']);
                break;
            case self::PAY_GIVE:
                $res = $this->payGive($member_id);
                return ds_arr($res['code'], $res['msg'], $res['result']);
                break;
            case self::REAL_VERIFY_GIVE:
                $res = $this->realVerifyGive($member_id);
                return ds_arr($res['code'], $res['msg'], $res['result']);
            default:
                break;
        }
    }

    /**
     * User: Simony
     * Function:注册赠送(赠送给下级)
     * @param $member_id
     * @param $superior_member_id
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function registerGive($member_id)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $superior_member = $memberModel->getInfoByID($member['parent_id']);
        if (!$superior_member) return ds_arr(ERROR, '上级用户不存在');

        $give_package = moduleConfig('give_package');
        $package_id = $give_package['register'][$superior_member['sex']][$superior_member['type']] ?? 0; //give_package[register][上级性别：1][上级用户类型：0]
        $give_package_id = intval($package_id);
        if ($give_package_id == 0) return ds_arr(SUCCESS, '赠送无'); //注意这里是success


        $packageModel = model('common/package/Package');
        $package = $packageModel->getInfoByID($package_id);
        if (!$package) return ds_arr(SUCCESS, '赠送的套餐不存在'); //注意这里是success


        //套餐购买记录
        $packageBuyLogModel = model('common/package/PackageBuyLog');
        $expire_end_time = $packageBuyLogModel->getMax(['member_id' => $member_id], 'expire_end_time'); //最大失效时间

        $current_time = time();
        $expire_start_time = $expire_end_time > $current_time ? $expire_end_time + 1 : $current_time + 1;

        //添加套餐记录
        $expire_end_time = $expire_start_time + $package['day'] * 86400;
        $price = $package['price'];
        $add_buy_package_data = [
            'package_id' => $package_id,
            'order_sn' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
            'member_id' => $member_id,
            'pay_type' => 0,  //0余额支付
            'state' => 1,
            'price' => 0,
            'create_time' => $current_time,
            'pay_time' => $current_time,
            'desc' => '赠送' . $package['name'] . ',为您节省' . $price . '金币',
            'expire_start_time' => $expire_start_time,
            'expire_end_time' => $expire_end_time,
            'type' => 1, //注册赠送
        ];
        $add_buy_package_res = $packageBuyLogModel->add($add_buy_package_data);

        if (!$add_buy_package_res) return ds_arr(ERROR, '赠送套餐失败'); //注意这里也让他通过


        $content = '恭喜您成功注册无界社区，获得' . $package['day'] . '天vip会员';
        model('common/message/Message')->addMessage(-1, $member_id, $member_id, 0, $content);
        model('common/Noticle', 'logic')->sendTxtSysNotice($member_id, $content, 7);
        return ds_arr(SUCCESS, '赠送成功');
    }


    /**
     * User: Simony
     * Function:购买赠送(赠送给上级)
     * @param $member_id
     * @param $superior_member_id
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function payGive($member_id)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $superior_member = $memberModel->getInfoByID($member['parent_id']);
        if (!$superior_member) return ds_arr(ERROR, '上级用户不存在');

        $packageBuyLogModel = model('common/package/PackageBuyLog');
        //检查下级有没有买过套餐
        if ($packageBuyLogModel->isExist(['member_id' => $member_id]) === false) return ds_arr(ERROR, '用户首次购买才赠送给上级');

        //获取配置
        $give_package = moduleConfig('give_package');
        $package_id = $give_package['sub_pay_package'][$superior_member['sex']][$superior_member['type']] ?? 0; //give_package[sub_pay_package][上级性别：1][上级用户类型：0]
        $limit_num = $give_package['num'][$superior_member['type']] ?? 0; //give_package[num][上级用户类型即：0]
        $give_package_id = intval($package_id);
        $limit_num = intval($limit_num);

        $packageModel = model('common/package/Package');
        if ($give_package_id == 0) return ds_arr(SUCCESS, '赠送无'); //注意这里是success
        $package = $packageModel->getInfoByID($package_id);
        if (!$package) return ds_arr(SUCCESS, '赠送的套餐不存在'); //注意这里是success


        //套餐购买记录
        $packageBuyLogModel = model('common/package/PackageBuyLog');
        if ($packageBuyLogModel->getCount(['member_id' => $superior_member['id'], 'type' => 2]) >= $limit_num) return ds_arr(SUCCESS, '赠送次数够了，无需重复赠送'); //注意这里是success

        $expire_end_time = $packageBuyLogModel->getMax(['member_id' => $superior_member['id']], 'expire_end_time'); //最大失效时间
        $current_time = time();
        $expire_start_time = $expire_end_time > $current_time ? $expire_end_time + 1 : $current_time + 1;

        //添加套餐记录
        $expire_end_time = $expire_start_time + $package['day'] * 86400;
        $price = $package['price'];
        $add_buy_package_data = [
            'package_id' => $package_id,
            'order_sn' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
            'member_id' => $superior_member['id'],
            'pay_type' => 0,  //0余额支付
            'state' => 1,
            'price' => 0,
            'create_time' => $current_time,
            'pay_time' => $current_time,
            'desc' => '下级用户购买，赠送您' . $package['name'] . '，为了节省' . $price . '金币',
            'expire_start_time' => $expire_start_time,
            'expire_end_time' => $expire_end_time,
            'type' => 2, //购买赠送
        ];
        $add_buy_package_res = $packageBuyLogModel->add($add_buy_package_data);

        if (!$add_buy_package_res) return ds_arr(ERROR, '赠送套餐失败'); //注意这里也让他通过

        $content = $member['nickname'] . '首次购买了vip会员套餐，奖励您' . $package['day'] . '天vip会员。';
        model('common/message/Message')->addMessage(-1, $superior_member['id'], $member_id, 0, $content);
        model('common/Noticle', 'logic')->sendTxtSysNotice($superior_member['id'], $content, 7);
        return ds_arr(SUCCESS, '赠送成功');
    }


    /**
     * User: Simony
     * Function:实名认证赠送
     * @param $member_id
     * @param $superior_member_id
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function realVerifyGive($member_id)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $superior_member = $memberModel->getInfoByID($member['parent_id']);
        if (!$superior_member) return ds_arr(ERROR, '上级用户不存在');

        $give_package = moduleConfig('give_package');

        //先送认证用户
        //give_package[real_verify][real][认证用户性别：1][上级性别：1]
        $package_id = $give_package['real_verify']['real'][$member['sex']][$superior_member['sex']] ?? 0; //赠送的套餐
        $package_id = intval($package_id);
        $packageModel = model('common/package/Package');
        $package = $packageModel->getInfoByID($package_id);
        $packageBuyLogModel = model('common/package/PackageBuyLog');
        if ($package) {
            $expire_end_time = $packageBuyLogModel->getMax(['member_id' => $member_id], 'expire_end_time'); //最大失效时间
            $current_time = time();
            $expire_start_time = $expire_end_time > $current_time ? $expire_end_time + 1 : $current_time + 1;
            //添加套餐记录
            $expire_end_time = $expire_start_time + $package['day'] * 86400;
            $price = $package['price'];
            $add_buy_package_data = [
                'package_id' => $package_id,
                'order_sn' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                'member_id' => $member_id,
                'pay_type' => 0,  //0余额支付
                'state' => 1,
                'price' => 0,
                'create_time' => $current_time,
                'pay_time' => $current_time,
                'desc' => '您进行了实名认证,赠送' . $package['name'] . ',为您节省' . $price . '金币',
                'expire_start_time' => $expire_start_time,
                'expire_end_time' => $expire_end_time,
                'type' => 3, //注册赠送
            ];
            $add_buy_package_res = $packageBuyLogModel->add($add_buy_package_data);
            if (!$add_buy_package_res) return ds_arr(ERROR, '赠送套餐失败'); //注意这里也让他通过

            $content = '恭喜您通过了真人认证，获得' . $package['day'] . '天vip会员。';
            model('common/message/Message')->addMessage(-1, $member_id, $member_id, 0, $content);
            model('common/Noticle', 'logic')->sendTxtSysNotice($member_id, $content, 7);

        }

        //再送上级用户
        $package_id = $give_package['real_verify']['superior'][$member['sex']][$superior_member['sex']] ?? 0; //赠送的套餐
        $package = $packageModel->getInfoByID($package_id);
        if ($package) {
            $expire_end_time = $packageBuyLogModel->getMax(['member_id' => $superior_member['id']], 'expire_end_time'); //最大失效时间
            $current_time = time();
            $expire_start_time = $expire_end_time > $current_time ? $expire_end_time + 1 : $current_time + 1;

            //添加套餐记录
            $expire_end_time = $expire_start_time + $package['day'] * 86400;
            $price = $package['price'];
            $add_buy_package_data = [
                'package_id' => $package_id,
                'order_sn' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                'member_id' => $superior_member['id'],
                'pay_type' => 0,  //0余额支付
                'state' => 1,
                'price' => 0,
                'create_time' => $current_time,
                'pay_time' => $current_time,
                'desc' => '您的下级' . $member['nickname'] . '进行了实名人证，赠送您' . $package['name'] . '，为了节省' . $price . '金币',
                'expire_start_time' => $expire_start_time,
                'expire_end_time' => $expire_end_time,
                'type' => 3, //购买赠送
            ];
            $add_buy_package_res = $packageBuyLogModel->add($add_buy_package_data);
            if (!$add_buy_package_res) return ds_arr(ERROR, '赠送套餐失败'); //注意这里也让他通过

            $content = $member['nickname'] . '通过了真人认证，获得' . $package['day'] . '天vip会员';
            model('common/message/Message')->addMessage(-1, $superior_member['id'], $member_id, 0, $content);
            model('common/Noticle', 'logic')->sendTxtSysNotice($superior_member['id'], $content, 7);
        }


        return ds_arr(SUCCESS, '赠送成功');
    }
}
